package Q219

import kotlin.math.abs

class Main {

}

/**
 * 存在重复元素
 * @author 23737
 * @date 2022.5.6
 */
fun main() {
    val array: IntArray = intArrayOf(1, 2, 3, 1, 2, 3)
    val containsNearbyDuplicate = Solution().containsNearbyDuplicate(array, 2)
    println(containsNearbyDuplicate)
}

class Solution {
    fun containsNearbyDuplicate(nums: IntArray, k: Int): Boolean {

        val map: MutableMap<Int, Int> = HashMap<Int, Int>()
        if (nums.isEmpty()) return false

        for (i in nums.indices) {
            if (map.containsKey(nums[i]) && Math.abs(map[nums[i]]!! - i) <= k) {
                return true
            }
            map[nums[i]] = i
        }
        return false
    }
}